import baseURL from "./config.js"
import showToast from "./util.js"

const request = {}
const headers = {}

let _loading = false;
//登录后请求
request.globalRequest = (url, method, data, power) => {
	//判断token是否存在
	//有token请求连接地址
	let token = uni.getStorageSync('token');
	if (!_loading) {
		uni.showLoading({
			title: "加载中" // 数据请求前loading
		});
		_loading = true
	}
	/*权限判断 因为有的接口请求头可能需要添加的参数不一样，所以这里做了区分
	    1 == 不通过access_token校验的接口
	    2 == 文件下载接口列表
	    3 == 验证码登录 */
	switch (power) {
		case 1:
			headers['Authorization'] = 'Basic a3N1ZGk6a3N1ZGk='
			break;
		case 2:
			headers['Authorization'] = 'Basic a3N1ZGlfcGM6a3N1ZGlfcGM='
			break;
		case 3:
			responseType = 'blob'
			break;
		default:
			headers['COOKIE_TOKEN'] = token
			break;
	}
	return uni.request({
		url: baseURL + url,
		method,
		data: data,
		contentType: "application/json;charset=UTF-8",
		dataType: "json",
		header: headers
	}).then(res => {
		if (!res[1]) {
			uni.showToast({
				title: "连接超时",
				icon: 'none'
			})
			return
		}
		if (res[1].data.code == 200) {
			uni.hideLoading();
			return res[1]
		} else {
			throw res[1].data
		}
	}).catch(parmas => {
		switch (parmas.code) {
			case 530:
				uni.hideLoading();
				if (_loading) {
					uni.showModal({
						title: '警告',
						content: parmas.message,
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								uni.setStorageSync("token", "");
								uni.reLaunch({
									url: "/pages/public/login"
								})
							}
						}
					});
					_loading = false;
				}
				return Promise.reject()
				break
			case 401:
				uni.clearStorageSync()
				break
			default:
				uni.showToast({
					title: parmas.message,
					icon: 'none'
				})
				return Promise.reject(parmas)
				break
		}
	})
}

//登录请求
request.globaSignIn = (url, method, data) => {
	/*权限判断 因为有的接口请求头可能需要添加的参数不一样，所以这里做了区分
	    1 == 不通过access_token校验的接口
	    2 == 文件下载接口列表
	    3 == 验证码登录 */
	return uni.request({
		url: baseURL + url,
		method,
		data: data,
		contentType: "application/json;charset=UTF-8",
		dataType: "json",
	}).then(res => {
		if (!res[1]) {
			uni.showToast({
				title: "连接超时",
				icon: 'none'
			})
			return
		} else if (res[1].data.code == 200) {
			return res[1]
		} else {
			throw res[1].data
		}
	}).catch(parmas => {
		switch (parmas.code) {
			case 401:
				uni.clearStorageSync()
				uni.showToast({
					title: parmas.message,
					icon: 'none'
				})
				return Promise.reject(parmas.message)
				break
			case 405:
				return Promise.reject(parmas)
				break
			case 500: 
				return Promise.reject(parmas.message)
				break
			default:
				uni.showToast({
					title: parmas.message,
					icon: 'none'
				})
				return Promise.reject()
				break
		}
	})
}

export default request
